﻿using System.Linq;
using Myotragus.Data.Containers;
using System;
using Myotragus.Data.Metadata;
using Myotragus.Data.Util;

namespace Myotragus.Data.Hbm
{
	public class AutomaticHbmGenerator : HbmGenerator, IAutomaticHbmGenerator
	{
		public AutomaticHbmGenerator(IEntitiesContainer entities, IEntityMapping mapping)
			: base(mapping)
		{
			Entities = entities;
		}

		protected IEntitiesContainer Entities { get; private set; }

		protected static readonly string StrFieldFormat = @"
		<property name=""{0}"" column=""{1}"" />
";

		protected virtual string GenerateAutoFieldMapping(IPropertyMapping p)
		{
			return string.Format(StrFieldFormat, p.PropertyName, p.ColumnName);
		}

		protected override Type ResolveRersistentType(Type interfaceType)
		{
			return Entities.ResolveType(interfaceType);
		}

		protected override string GenerateNonIdFieldsMappings(Type interfaceType)
		{
			var properties = Mapping.GetFields(interfaceType);
			return properties.Select(p => GenerateAutoFieldMapping(p)).Join();
		}
	}
}